<template>
  <div class="departments">
    <el-card class="mycard">
      <el-tabs>
        <el-tab-pane label="组织结构">
          <div class="box">
            <treetools
              :isTop="true"
              @changeAddShow="openAdd"
              :item="topitem"
            ></treetools>
            <hr />
            <el-tree :data="list" default-expand-all>
              <treetools
                slot-scope="{ data }"
                @refreshData="getDepartment"
                @changeAddShow="openAdd"
                @changeEditShow="openEdit"
                :item="data"
              ></treetools>
            </el-tree>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <addpanel
      ref="addpanle"
      :addshow.sync="addshow"
      :currentObj="currentObj"
      @updateList="getDepartment"
    ></addpanel>
  </div>
</template>

<script>
name: 'departments'
import { getDepartmentApi } from '@/api/departments.js'
export default {
  data () {
    return {
      topitem: {
        label: '传智教育'
      },
      list: [],
      addshow: false,
      currentObj: {}
    }
  },
  methods: {
    async getDepartment () {
      const res = await getDepartmentApi()
      this.list = this.tunData(res.data.depts, '')
      this.topitem = { ...res.data.depts[0], manager: '负责人' }
    },
    tunData (arr, pid) {
      let newarr = []
      arr.forEach(item => {
        if (item.pid == pid) {
          let children = this.tunData(arr, item.id)
          item.children = children
          newarr.push(item)
        }
      })
      return newarr
    },
    openEdit (item) {
      this.addshow = true
      this.currentObj = item
      // console.log(this.$refs.addpanle)
      this.$refs.addpanle.getItem(item.id)
    },
    openAdd (item) {
      this.addshow = true
      this.currentObj = item
    }
  },
  created () {
    this.getDepartment()
  },
  components: {
    treetools: () => import('./components/treetool.vue'),
    addpanel: () => import('./components/addpanel.vue')
  }
}
</script>

<style lang="scss" scoped>
.departments {
  margin: 20px;
  .mycard {
    padding: 20px;
  }
  .box {
    padding: 40px 90px 0;
  }
}
</style>
